package cn.tedu.egnotice2.controller;

import cn.tedu.egnotice2.base.response.JsonResult;
import cn.tedu.egnotice2.base.response.StatusCode;
import cn.tedu.egnotice2.mapper.NoticeMapper;
import cn.tedu.egnotice2.pojo.datatransferobject.NoticeAddParam;
import cn.tedu.egnotice2.pojo.datatransferobject.NoticeAddQuery;
import cn.tedu.egnotice2.pojo.datatransferobject.NoticeUpdateParam;
import cn.tedu.egnotice2.pojo.entity.Notice;
import cn.tedu.egnotice2.pojo.valueobject.NoticeDetailInfoVO;
import cn.tedu.egnotice2.pojo.valueobject.NoticeListVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Random;

@RestController
@RequestMapping("v1/notice")
@Slf4j
public class NoticeController {
    @Autowired
    private NoticeMapper noticeMapper;

    @PostMapping("/add")
    public JsonResult insertNotice(@RequestBody NoticeAddParam noticeAddParam) {
        log.debug("noticeAddParam:" + noticeAddParam);
        Notice notice = new Notice();
        BeanUtils.copyProperties(noticeAddParam, notice);
        notice.setUserId(1L);
        notice.setCreateTime(new Date());
        notice.setUpdateTime(new Date());
        log.debug("notice:" + notice);
        int num = noticeMapper.addNotice(notice);
        return num > 0 ? JsonResult.alright() : new JsonResult(StatusCode.OPERATION_FAILED);
    }

    @GetMapping("/list")
    public JsonResult selectNotice(NoticeAddQuery noticeAddQuery) {
        log.debug("noticeAddQuery:" + noticeAddQuery);
        List<NoticeListVO> noticeListVOS = noticeMapper.queryNotice(noticeAddQuery);
        return noticeListVOS.size() > 0 ? JsonResult.alright(noticeListVOS) : new JsonResult(StatusCode.OPERATION_FAILED);
    }

    @GetMapping("/detail")
    public JsonResult selectDetailNotice(Long id) {
        log.debug("id:" + id);
        NoticeDetailInfoVO noticeDetailInfoVO = noticeMapper.queryDetail(id);
        return noticeDetailInfoVO != null ? JsonResult.alright(noticeDetailInfoVO) : new JsonResult(StatusCode.OPERATION_FAILED);
    }

    @PostMapping("/del")
    public JsonResult deleteNotice(Long id) {
        log.debug("id:" + id);
        int num = noticeMapper.delNotice(id);
        return num > 0 ? JsonResult.alright() : new JsonResult(StatusCode.OPERATION_FAILED);
    }

    @PostMapping("/update")
    public JsonResult updateNotice(@RequestBody NoticeUpdateParam noticeUpdateParam) {
        log.debug("noticeUpdateParam:" + noticeUpdateParam);
        Notice notice = new Notice();
        BeanUtils.copyProperties(noticeUpdateParam, notice);
        notice.setUpdateTime(new Date());
        int num = noticeMapper.upNotice(notice);
        return num > 0 ? JsonResult.alright() : new JsonResult(StatusCode.OPERATION_FAILED);
    }
}
